  var sseUri;
  var sse;
  var consoleLog;
  var connectBut;
  var disconnectBut;
  var clearLogBut;

  function sseHandlePageLoad()
  {
     if (!!window.EventSource)
    {
      document.getElementById('support').style.display = 'block';
    }
    else
    {
      document.getElementById('noSupport').style.display = 'block';
    }

    sseUri = document.getElementById('sseUri');
    initializeLocation();

    // Connect if the user presses enter in the connect field.
    sseUri.onkeypress = function(e){
      if (!e) {
        e = window.event;
      }
      var keyCode = e.keyCode || e.which;
      if (keyCode == '13'){
        doConnect();
        return false;
      }
    }

    connectBut = document.getElementById('connect');
    connectBut.onclick = doConnect;

    disconnectBut = document.getElementById('disconnect');
    disconnectBut.onclick = doDisconnect;

    consoleLog = document.getElementById('consoleLog');

    clearLogBut = document.getElementById('clearLogBut');
    clearLogBut.onclick = clearLog;

    setGuiConnected(false);
  }

  function initializeLocation() {
    // See if the location was passed in.
    sseUri.value = getParameterByName('location');
    if (sseUri.value != '') {
      return;
    }
    var httpScheme = 'http:';
    if (window.location.protocol.toString() == 'https:') {
        httpScheme = 'https:';
    }
    var ssePort = (window.location.port.toString() == '' ? '' : ':'+window.location.port)
    sseUri.value = httpScheme+'//localhost'+ ssePort
  }


  function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i'),
    results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
  }

  function doConnect()
  {
    var uri = sseUri.value;
    sse = new EventSource(uri);
    console.log("new==>" + sse.readyState)
    sse.onopen = function(evt) { onOpen(evt) };
    sse.onmessage = function(evt) { onMessage(evt) };
    sse.onerror = function(evt) { onError(evt) };
  }

  function doDisconnect()
  {
    sse.close();
    console.log("disconnect==>" + sse.readyState)
    onClose();
  }

  function logTextToConsole(text) {
    var span = document.createTextNode(text);
    logElementToConsole(span);
  }

  // label is a string like 'Info' or 'Error'.
  function logErrorToConsole(label, text) {
    var span = document.createElement('span');
    span.style.wordWrap = 'break-word';
    span.style.color = 'red';
    span.innerHTML = '<strong>'+label+':</strong> ';

    var text = document.createTextNode(text);
    span.appendChild(text);

    logElementToConsole(span);
  }

  function logElementToConsole(element) {

    var p = document.createElement('p');
    p.style.wordWrap = 'break-word';
    p.appendChild(element);

    consoleLog.appendChild(p);

    while (consoleLog.childNodes.length > 50)
    {
      consoleLog.removeChild(consoleLog.firstChild);
    }

    consoleLog.scrollTop = consoleLog.scrollHeight;
  }

  function onOpen(e)
  {
    //客户端request timeout时每次重连都会走该方法, readyState (CONNECTING:0, OPEN:1, CLOSED:2
    console.log("open==>" + sse.readyState)
    logTextToConsole('CONNECTED');
    setGuiConnected(true);

    //打印对象有哪些属性
//    console.log(Object.keys(e));
//    for (var i in e) {
//        console.log("props=>" + i + ":" + e[i]);
//    }
  }

  function onClose()
  {
    console.log("close==>" + sse.readyState)
    logTextToConsole('DISCONNECTED');
    setGuiConnected(false);
  }

  function onMessage(evt)
  {
    console.log("msg==>" + evt.data)
    var span = document.createElement('span');
    span.style.wordWrap = 'break-word';
    span.style.color = 'blue';
    span.innerHTML = 'RECEIVED: ';

    var message = document.createTextNode("lastEventId=>" + evt.lastEventId + " origin=> "
        + evt.origin + " data=> " + evt.data);
    span.appendChild(message);

    logElementToConsole(span);
  }

  function onError(e)
  {
    //每次收到一次数据以后，客户端就会处于connecting，此时会走到onerror方法
    if (e.readyState == EventSource.CLOSED)
        { console.log("error closed==>" + sse.readyState); }
    else
        { console.log("error==>" + sse.readyState); }
    logErrorToConsole('ERROR', sse.readyState);

    //打印对象有哪些属性
//    console.log(Object.keys(e.target));
//    for (var i in e.srcElement) {
//        console.log("props=>" + i + ":" + e.srcElement[i]);
//    }
  }

  function setGuiConnected(isConnected)
  {
    sseUri.disabled = isConnected;
    connectBut.disabled = isConnected;
    disconnectBut.disabled = !isConnected;
    var labelColor = 'black';
    if (isConnected)
    {
      labelColor = '#999999';
    }
  }

  function clearLog()
  {
    while (consoleLog.childNodes.length > 0)
    {
     consoleLog.removeChild(consoleLog.lastChild);
    }
  }

window.addEventListener('load', sseHandlePageLoad, false);